package com.lovo.bbs.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lovo.bbs.vo.LoginVo;

/**
 * 注销登陆Servlet
 * 
 * @author tiancen2001
 * 
 */
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 7324707010422823305L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//cookie立即过期
		 Cookie cookie[] = request.getCookies();
		 for(int i = 0; i < cookie.length; i++)
	        {
	            if("cookieName".equals(cookie[i].getName()))
	            {
	                cookie[i].setMaxAge(0);
	                response.addCookie(cookie[i]);
	            }
	            if("cookiePassword".equals(cookie[i].getName()))
	            {
	                cookie[i].setMaxAge(0);
	                response.addCookie(cookie[i]);
	            }
	    }
		 
		// 用户名
		String username = request.getParameter("logedusername");
		String toindex = request.getParameter("toindex");//是否转向到首页
          
		if (username != null) {
			// 清除登录会话变量
			HttpSession session = request.getSession();
			session.removeAttribute("loginvo");
			session.removeAttribute("moderator");
			session.removeAttribute("admin");
			// 将用户从在线列表清除
			ServletContext contex = request.getSession().getServletContext();
			HashMap<String, LoginVo> onlineUser = null;
			onlineUser = (HashMap<String, LoginVo>) contex
					.getAttribute("onlineUser");
			onlineUser.remove(username);
			contex.setAttribute("onlineUser", onlineUser);

			if(toindex!=null){
				response.sendRedirect("index.jsp");
			}else{
				response.setContentType("text/html;charset=utf-8");
				response.setCharacterEncoding("utf-8");
				PrintWriter out = response.getWriter();
				out.println("1");// 返回信息
				out.flush();
				out.close();
			}
		}
	}

}
